package com.shangyitong.service_oss.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.shangyitong.service_oss.service.FileService;
import com.shangyitong.service_oss.utils.ConstantOssPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Override
    public String fileUpload(MultipartFile file) {
        String endpoint = ConstantOssPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String secret = ConstantOssPropertiesUtils.SECRET;
        String bucket = ConstantOssPropertiesUtils.BUCKET;
        String url;
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secret);
        try {
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值,使用uuid,添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            //按照当前日期,创建文件夹,上传到创建文件夹里面
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;
            //调用方法实现上传
            ossClient.putObject(bucket, fileName, inputStream);
            //关闭OSSclient
            ossClient.shutdown();
            //上传之后文件路径
            url = "https://" + bucket + "." + endpoint + "/" + fileName;
            //返回数据
            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
